package cn.gjxblog.controller;


import cn.gjxblog.api.AgencyServerFegin;
import cn.gjxblog.api.FileServiceFegin;
import cn.gjxblog.api.SmsServiceFegin;
import cn.gjxblog.api.UserServiceFegin;
import cn.gjxblog.common.model.HttpResult;
import cn.gjxblog.common.model.PageCondition;
import cn.gjxblog.common.model.PageData;
import cn.gjxblog.common.utils.RandomUtils;
import cn.gjxblog.inteceptor.TokenInterceptor;
import cn.gjxblog.model.ResultMsg;
import cn.gjxblog.model.UserContext;
import cn.gjxblog.model.UserHelper;
import cn.gjxblog.model.entity.Agency;
import cn.gjxblog.model.entity.User;
import cn.gjxblog.model.entity.UserMsg;
import cn.gjxblog.model.vo.UserMsgVo;
import cn.gjxblog.model.vo.UserVO;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2018/12/7 16:53
 */
@Controller
@RequestMapping("/accounts")
public class UserController {


    @Value("${domain.name}")
    private String domainName;


    @Autowired
    private FileServiceFegin fileServerFegin;

    @Autowired
    private UserServiceFegin userServerFegin;

    @Autowired
    private AgencyServerFegin agencyServerFegin;

    @Autowired
    private SmsServiceFegin smsServiceFegin;

    @PostMapping("/uploadHeadImg")
    public ResponseEntity uploadHeadImg(MultipartFile file){
        try {
            String path = uploadFile(file);
            User user = new User();
            user.setId(UserContext.getUser().getId());
            user.setAvatar(path);
            userServerFegin.updateUser(user);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok().build();
    }

    @RequestMapping("/myReciveMsg")
    public String getUserMsgByUserId( PageCondition pageCondition,ModelMap modelMap){

        HttpResult<PageInfo<UserMsg>> pageInfoHttpResult = userServerFegin.queryUserMsgByAgentId(UserContext.getUser().getId(),pageCondition);
        PageInfo<UserMsg> result = pageInfoHttpResult.getResult();


        List<UserMsg> list = result.getList();

        List<UserMsgVo> users = new ArrayList<>();
        for (UserMsg userMsg : list) {
            String userId = userMsg.getUserId();
            User user = userServerFegin.getUserById(userId).getResult();
            UserMsgVo userMsgVo = new UserMsgVo();
            userMsgVo.setUser(user);
            userMsgVo.setUserMsg(userMsg);
            users.add(userMsgVo);
        }

        PageData<UserMsgVo> pageData = PageData.buildPage(users, result.getTotal(), pageCondition.getPageSize(), pageCondition.getPageNum());

        modelMap.put("ps",pageData) ;

        return "/user/accounts/reciveMsglist";

    }
    @RequestMapping("/myleaveMsg")
    public String queryUserMsgByAgentId(PageCondition pageCondition,ModelMap modelMap){

        HttpResult<PageInfo<UserMsg>> pageInfoHttpResult = userServerFegin.queryUserMsgByUserId(UserContext.getUser().getId(),pageCondition);
        PageInfo<UserMsg> result = pageInfoHttpResult.getResult();

        List<UserMsg> list = result.getList();

        List<UserMsgVo> users = new ArrayList<>();
        for (UserMsg userMsg : list) {
            String agentId = userMsg.getAgentId();
            User user = userServerFegin.getUserById(agentId).getResult();
            UserMsgVo userMsgVo = new UserMsgVo();
            userMsgVo.setUser(user);
            userMsgVo.setUserMsg(userMsg);
            users.add(userMsgVo);
        }

        PageData<UserMsgVo> pageData = PageData.buildPage(users, result.getTotal(), pageCondition.getPageSize(), pageCondition.getPageNum());

        modelMap.put("ps",pageData) ;

        return "/user/accounts/leaveMsglist";

    }
    //-----------------注册流程----------------
    @RequestMapping(value = "/register",method = {RequestMethod.POST,RequestMethod.GET})
    public String register(UserVO account, String smscode,HttpSession session) throws IOException {
        //注册页面请求
        if(account == null || account.getName() == null){
            return "/user/accounts/register";
        }
        //注册逻辑请求
        //校验用户信息是否符合要求
        ResultMsg retMsg = UserHelper.validate(account);
        if(retMsg.isSuccess()){
           /* if(StringUtils.isNotBlank(smscode)){
                String code = (String) session.getAttribute("smscode");
                if(!StringUtils.equals(code,smscode)){
                    return "redirect:/accounts/register?" + ResultMsg.errorMsg("验证码错误").asUrlParams();
                }
            }else{
                return "redirect:/accounts/register?" + ResultMsg.errorMsg("验证码不能为空").asUrlParams();
            }*/
            //查询用户是否存在
            boolean flag = isUserExist(account.getPhone());
            if(!flag){
                return "redirect:/accounts/register?" + ResultMsg.errorMsg("手机号已被占用").asUrlParams();
            }
            //默认头像
            account.setAvatar("http://img.gjxblog.cn/defaulthead.jpg");
            //调用用户服务添加用户API
            userServerFegin.addUser(account,"");
            return "redirect:/index?"+ResultMsg.successMsg("注册成功,请登录").asUrlParams();
        }
        return "redirect:/accounts/register?" + ResultMsg.errorMsg("参数错误").asUrlParams();
    }

    /**
     * 向指定用户发送验证码
     * @param phone
     * @return
     */
    @RequestMapping(value = "/sendRegistCode",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public ResponseEntity sendRegistCode(HttpSession httpSession,String phone){
        //生成6位验证码
        String code = RandomUtils.getRandNumberStr(6);
        //Session存储验证码
        httpSession.setAttribute("smscode",code);
        //调用公共服务中发送短信API
        smsServiceFegin.sendSms(code,phone);
        return ResponseEntity.ok().build();
    }


    public String uploadFile(MultipartFile file) throws IOException {
        HttpResult responseVO = fileServerFegin.upload(file.getBytes(),file.getOriginalFilename());
        return (String) responseVO.getResult();
    }

    public boolean isUserExist(String email) {
        HttpResult<User> responseVO = userServerFegin.getUserByEmail(email);
        User result = responseVO.getResult();
        if(result != null){
            return false;//不存在
        }
        return true;//存在
    }
    /**
     * 激活接口
     */
    @GetMapping("/verify")
    public String verify(String key){
        try {
            userServerFegin.enable(key);
            return "redirect:/index?" + ResultMsg.successMsg("激活成功").asUrlParams();
        }catch (Exception e){
            return "redirect:/accounts/signin?" + ResultMsg.errorMsg("激活失败,请确认链接是否过期").asUrlParams();
        }
    }

    //---------------登录流程--------------
    @RequestMapping(value = "/signin",method = {RequestMethod.POST,RequestMethod.GET})
    public String signin(String username,String smscode,String password, String target, HttpServletResponse response,HttpSession session){
        //登录页面请求
        if (username == null || password == null) {
            return "/user/accounts/signin";
        }

        /*if(StringUtils.isNotBlank(smscode)){
            String code = (String) session.getAttribute("smscode");
            if(!StringUtils.equals(code,smscode)){
                return "redirect:/accounts/signin?" + ResultMsg.errorMsg("验证码错误").asUrlParams();
            }
        }else{
            return "redirect:/accounts/signin?" + ResultMsg.errorMsg("验证码不能为空").asUrlParams();
        }*/

        //登录流程请求
        User queryUser = new User(username,password);
        //调用用户服务，进行认证
        String token = userServerFegin.auth(queryUser).getResult();
        //认证失败
        if (token == null) {
            return "redirect:/accounts/signin?" + "username=" + username + "&" + ResultMsg.errorMsg("用户名或密码错误").asUrlParams();
        }else {

            //认证成功，采用cookie保存token
            Cookie cookie = new Cookie(TokenInterceptor.TOKEN_COOKIE, token);
            cookie.setPath("/");
            cookie.setHttpOnly(false);
            response.addCookie(cookie);
            return  StringUtils.isNotBlank(target) ? "redirect:" + target : "redirect:/index";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpServletResponse httpServletResponse){
        Cookie cookie = new Cookie(TokenInterceptor.TOKEN_COOKIE, "");
        cookie.setPath("/");
        cookie.setHttpOnly(false);
        httpServletResponse.addCookie(cookie);

        return "redirect:/index";
    }

    //---------------个人信息----------------
    @GetMapping(value="/profile")
    public String profile(Model model){
        List<Agency> list = agencyServerFegin.queryAgency().getResult();
        model.addAttribute("agencyList", list);
        return "/user/accounts/profile";
    }


    @PostMapping("/changePassword")
    public String changePassword(String email, String password, String newPassword,
                                 String confirmPassword) {

        User user = userServerFegin.getUserByEmail(email).getResult();
        if (user == null || !confirmPassword.equals(newPassword)) {
            return "redirect:/accounts/profile?" + ResultMsg.errorMsg("密码错误").asUrlParams();
        }
        User updateUser = new User();
        updateUser.setPasswd(newPassword);
        updateUser.setEmail(email);
        userServerFegin.updateUser(updateUser);
        return "redirect:/accounts/profile?" + ResultMsg.successMsg("更新成功").asUrlParams();
    }

    @PostMapping(value="/profileSubmit")
    public String profileSubmit(User updateUser,ModelMap  model){
        String id = UserContext.getUser().getId();
        updateUser.setId(id);
        User user = userServerFegin.updateUser(updateUser).getResult();
        return "redirect:/accounts/profile?" + ResultMsg.successMsg("更新成功").asUrlParams();
    }

    /**
     * 忘记密码
     * @param username
     * @param modelMap
     * @return
     */
    @RequestMapping("/remember")
    public String remember(String username,ModelMap modelMap){
        if (StringUtils.isBlank(username)) {
            return "redirect:/accounts/signin?" + ResultMsg.errorMsg("邮箱不能为空").asUrlParams();
        }
        userServerFegin.resetNotify(username,"http://" + domainName + "/accounts/reset");
        modelMap.put("email", username);
        return "/user/accounts/remember";
    }

    /**
     * 重置密码
     * @param key
     * @param modelMap
     * @return
     */
    @RequestMapping("/reset")
    public String reset(String key,ModelMap modelMap){
       /* String email = userServerFegin.getEmailByKey(key).getResult();
        if (StringUtils.isBlank(email)) {
            return "redirect:/accounts/signin?" + ResultMsg.errorMsg("重置链接已过期");
        }
        modelMap.put("email", email);
        modelMap.put("success_key", key);*/
        return "/user/accounts/reset";
    }

    @RequestMapping(value="/resetSubmit",method={RequestMethod.POST,RequestMethod.GET})
    public String resetSubmit(UserVO user,String oldPwd,HttpServletResponse response){
        //oldPwd 校验

        ResultMsg retMsg = UserHelper.validateResetPassword(user.getPasswd(), user.getConfirmPasswd());
        if (!retMsg.isSuccess() ) {
            return "redirect:/accounts/reset?"+ retMsg.asUrlParams();
        }
         userServerFegin.resetPwd(UserContext.getUser().getId(),user.getPasswd()).getResult();
        //退出登录
        Cookie cookie = new Cookie(TokenInterceptor.TOKEN_COOKIE, "");
        cookie.setPath("/");
        cookie.setHttpOnly(false);
        response.addCookie(cookie);
        return "redirect:/index?" + ResultMsg.successMsg("修改密码成功,重新登录").asUrlParams();
    }
}
